﻿using System.Web.Mvc;
using MRGSP.SurveyMaster.Core;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Service;
using MRGSP.SurveyMaster.Infra.Dto;
using Omu.ValueInjecter;

namespace MRGSP.SurveyMaster.WebUI.Controllers
{
    [Authorize(Roles = The.Admin)]
    public class SurveyController : Controller
    {
        private readonly ISurveyService surveyService;
        private readonly IQuestionService questionService;

        public SurveyController(ISurveyService surveyService, IQuestionService questionService)
        {
            this.surveyService = surveyService;
            this.questionService = questionService;
        }

        public ActionResult Index(int? page)
        {
            return View(surveyService.GetPageable(page ?? 1, 10));
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(SurveyInput input)
        {
            if (!ModelState.IsValid)
                return View(input);
            var id = surveyService.Create((Survey) new Survey().InjectFrom(input));
            return RedirectToAction("EditContent", new {id});
        }

        public ActionResult Edit(long id)
        {
            var input = new SurveyInput();
            return View("create", input.InjectFrom( surveyService.Get(id)));
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(SurveyInput input)
        {
            if (!ModelState.IsValid)
                return View("create", input);

            surveyService.Update((Survey)new Survey().InjectFrom(input));
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult EditContent(long id)
        {
            ViewData["survey"] = id;
            var questions = questionService.GetBySurveyId(id);
            return View(questions);
        }

        [HttpPost]
        public ActionResult Delete(long id)
        {
            surveyService.Delete(id);
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Activate(long id)
        {
            surveyService.Activate(id);
            return RedirectToAction("index");
        }

        [HttpPost]
        public ActionResult Deactivate(long id)
        {
            surveyService.Deactivate(id);
            return RedirectToAction("index");
        }
    }
}